<?php

namespace app\models;

use app\models\constant\Status;
use app\models\role_supplier\AdminRole;
use app\models\role_supplier\Permission;
use app\models\role_supplier\RoleMenu;
use app\validator\AdminSupplierValidator;
use Yii;

/**
 * This is the model class for table "admin".
 *
 * @property int $id
 * @property string $username
 * @property string $password
 * @property string $role 角色
 * @property string $create_time
 * @property string $update_time
 * @property string $avatar
 * @property string $name
 */
class AdminSupplier extends \yii\db\ActiveRecord
{
    // use Status;

    /**
     * status list
     * @var int[]
     */
    public static $statusMapping = [
        'ALL'       => -1,
        'OK'        => 1,
        'CLOSE'     => 0,
        'DELETE'    => -99,
    ];

    /**
     * status display list
     * @var int[]
     */
    public static $statusMappingDisplay = [
        '全部'       => -1,
        '正常'       => 1,
        '待审核'       => 0,
        // '删除'       => -99,
    ];

    /**
     * Status list
     *
     * @return array
     */
    public static function statusList()
    {
        $list = [];
        foreach (self::$statusMappingDisplay as $key => $value) {
            $list[] = [
                'label' => $key,
                'value' => $value
            ];
        }

        return $list;
    }

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'admin_supplier';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['create_time', 'update_time'], 'safe'],
            [['username'], 'string', 'max' => 50],
            [['password'], 'string', 'max' => 32],
            [['role', 'avatar'], 'string', 'max' => 255],

            // [['username'], 'unique', 'message' => '此用户名已经存在'],

            [['username'], AdminSupplierValidator::class, 'on' => 'edit'],
            [['username'], 'validateLength', 'on' => 'edit'],

            [['can_delete'], 'safe'],

            // 审核状态
            [['status', 'name', 'sort'], 'safe'],


            [['mobile', 'nickname', 'address', 'discount', 'category_id', 'desc', 'p_id', 'address_id'], 'safe'],

            // 供应商和线下门店放一起的
            [['is_shop'], 'safe'],
        ];
    }

    public function validateLength($attribute, $params)
    {
        if (strlen($this->$attribute) < 3) {
            $this->addError($attribute, $this->attributeLabels()[$attribute] . '长度不能小于3');
        }
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'role' => 'Role',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'avatar' => 'Avatar',
            'nickname' => 'Nickname',
        ];
    }

    /**
     * Save timestamp
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    public static function login($username, $password)
    {
        return self::find()
            ->where(['username' => $username, 'password' => $password])
            ->andWhere(['status' => [1, 0]])
            ->orderBy(['id' => SORT_DESC])
            ->one();
    }

    public static function getInfo($id, $username)
    {
        $user = self::find()
            ->where(['id' => $id])
            ->andWhere(['username' => $username])
            ->asArray()
            ->one();

        if ($user) {
            unset($user['password']);
            // 需要定义角色(前端需要)
            // $user['roles'] = [$user['role']];


            // 权限
            $user['roles'] = self::getMenuListByRole($user['id']);

            // 这里不要用权限(供应商主号)
            if ($user['p_id'] == 0) {
                $user['roles'] = [$user['role']];
            }

            $user['username'] = $user['username'];

            // 商家名称
            if ($user['p_id'] == 0) {
                $pid = $user['id'];
            } else {
                $pid = $user['p_id'];
            }
            $name = self::find()
                ->where(['id' => $pid])
                ->select(['name'])
                ->scalar();

            $user['name'] = mb_substr($name, 0, 10, 'UTF-8');
            // $user['avatar'] = $user['avatar'];

            return $user;
        }

        return false;
    }

    // 直接把菜单列表给前端
    public static function getMenuListByRole($user_id)
    {

        // 用户有哪些角色
        $role_ids = AdminRole::find()
            ->where(['admin_id' => $user_id])
            ->select(['role_id'])
            ->column();

        // var_dump($role_ids);exit;

        // 角色有哪些菜单
        $menu_ids = Permission::find()
            ->where(['role_id' => $role_ids])
            ->select(['menu_id'])
            ->column();
        // var_dump($menu_ids);exit;

        // 菜单有哪些名称(这里拿链接,去掉首/, 对应前端)
        $urls = RoleMenu::find()
            ->where(['id' => $menu_ids])
            ->select(['url'])
            ->column();

        // 去掉 /
        foreach ($urls as &$url) {
            $url = substr($url, 1);
        }

        // var_dump($urls);exit;

        return $urls;

    }

    // 证件
    public function getImage()
    {
        return $this->hasMany(SupplierImage::class, ['supplier_id' => 'id']);
    }

    // 店铺
    public function getDescImage()
    {
        return $this->hasMany(SupplierImageDesc::class, ['supplier_id' => 'id']);
    }

    // 分类
    public function getCategory()
    {
        return $this->hasOne(SupplierCategory::class, ['id' => 'category_id']);
    }

    // 地区
    public function getAddress()
    {
        return $this->hasOne(SupplierAddress::class, ['id' => 'address_id']);
    }
}
